package com.alipay.rebate.shop.utils;

import cn.jpush.api.push.model.SMS;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.alipay.rebate.shop.dao.mapper.AppSettingsMapper;
import com.alipay.rebate.shop.helper.AppSettingsHelper;
import com.alipay.rebate.shop.pojo.mobilecode.SendSmsResponse;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

public class AliUtil {

    private static Logger logger = LoggerFactory.getLogger(AliUtil.class);

    private static final String APPID = "2019031663560224";
    private static final String PRIVATEKEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC+o9/vztWOtvS05rfYXTC5JCKFKCnf6IeAjliDSfU52kBNi+PsIOGYNEDpciAj3YbZiIx+GkANdm8d3ZJiiB/H4zYMj9gRZEbbXOC/tp0ipPjy4LKw2HwBcjjG1E2EJ7JmRVEZK5Fpoh9TPK/KuqmJ0P5vHGOi9aJHhrgkKsA0XvMT2g0dn5pTvD4nSWypuyBmYyrbGlprzFFKqMsIrqNX/iaWOCTQdoR1cXzG2ndm3MNT250zSOs3j8LKbzqtGW9QgyFy7WRs3r0fPaME9GuT2xoqA2H2W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aKN4Y42n1VmfpB0sLlcHWQGAbAbdhuiLAoGBAIZaRGqxYLNopsNUnrkLXm9cZEq9YIa6pUxFpd7ARaJtIhd59JrLjqWSGhQA8kEptKCdfy91Pqbpi7UiTxv6YhMO8PmGIetwYITEs5yXk4spFkBBypBp7ax0xeClrfp8xkTE5gmhIxaKGPiO+nciJBbW9qBHCOwFcd78PW111Em/";
    private static final String PUBLICKEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAklOdBc0WjpbG/O4mcGx/yyuJtC98XfDPQwV2VDem3+qN2cong+rCRQXefyOUlWWc8oH0crdpg04RilZIis3jmDZ+GE30ASxP/9OYy5IpM2xaCHOAGF6BB3RkxKTFWez4yn+FjRzRxArL7SV4b2JRskXzFgr3lXTauMo1+OgHUqR0dd25sQqkUJlyIyGqXOjbIEzfPdMNaz13dnqfmJqXaFaiubE4BBN/oOp2ZErC5FjI+dH6euG1BcbBNZmrETh3ZPWjpEFH1aYEriVegXlXaglYuLBw6D6UQdCJM5JUIlTGNOAGDr/ewtg7r0wgpS+G7bTz8EgrsqWygUKXvlPs8QIDAQAB";
    // for send sms
    private static final String SMS_ACCESSKEY_ID = "LTAI4G3fCu5zzEmkFdtNayAG";
    private static final String SMS_SECRET = "So65sc83ILDlb2ugxGJ5Lf61KVEdgN";
    private static final String SMS_DOMAIN = "dysmsapi.aliyuncs.com";
    private static final String SMS_ACTION = "SendSms";
    private static final String SMS_SIGN_NAME = "网购省钱验证";
    // 普通短信
    private static final String SMS_TEMPLATE_CODE = "SMS_101150084";
    private static final String SMS_TEMPLATE_PARAM = "{\"code\":\"123456\",\"product\":\"网购省钱\"}";
    private static final String SMS_VERSION = "2017-05-25";
    private final static String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
    private final static String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改

    private static final String SMS_WITH_TEMPLATE_CODE = "SMS_95460011";
    private static final String SMS_WITH_TEMPLATE_PARAM = "{\"name\":\"123456\", \"appname\":\"淘赚钱联盟\",\"reason\":\"654321\"}";

    // 港澳台/国际短信code
    private static final String SMS_INTERNATIONAL_CODE = "SMS_193247060";
    private static Gson gson = new Gson();

    /**
     * 发送验证码
     * @param phone 电话号码
     * @param code 验证码
     */
    public static SendSmsResponse sendSms(String phone,String code) throws ClientException {
        logger.debug("sending sms code");
        String templateParam = SMS_TEMPLATE_PARAM.replaceAll("123456",code);
        SendSmsResponse commonResponse = doSendSms(phone, templateParam, SMS_SIGN_NAME, SMS_TEMPLATE_CODE);
        return commonResponse;
    }

    /**
     * 发送国际短信
     * @param phone
     * @param code
     */
    public static SendSmsResponse sendInternationalSms(String phone,String code){
        logger.debug("sending sms code");
        String templateParam = SMS_TEMPLATE_PARAM.replaceAll("123456",code);
        SendSmsResponse commonResponse = doSendSms(phone, templateParam, SMS_SIGN_NAME, SMS_INTERNATIONAL_CODE);
        return commonResponse;
    }


    /**
     * 发送验证码
     * @param phone 电话号码
     * @param name 名称
     * @param reason 理由
     */
    public static SendSmsResponse sendWithDrawSms(String phone,String name, String reason,String signName, String templateCode) {
        logger.debug("sending sms code");
        String templateParam  =SMS_WITH_TEMPLATE_PARAM.replaceAll("123456",name)
            .replaceAll("654321",reason);
        SendSmsResponse sendSmsResponse = doSendSms(phone, templateParam, signName, templateCode);
        return sendSmsResponse;
    }

    public static SendSmsResponse doSendSms(String phone,String templateParam,String signName, String templateCode) {
        logger.debug("sending sms code");
        DefaultProfile profile = DefaultProfile.getProfile("default", SMS_ACCESSKEY_ID, SMS_SECRET);
//        DefaultProfile profile = DefaultProfile.getProfile("default", AppSettingsHelper.getSmsAccesskeyId(), AppSettingsHelper.getSmsSecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain(SMS_DOMAIN);
        request.setVersion(SMS_VERSION);
        request.setAction(SMS_ACTION);
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", templateParam);
        try {
            CommonResponse response = client.getCommonResponse(request);
            logger.debug("rsp is : {}"+response.getData());
            String data = response.getData();
            String substring = data.substring(data.indexOf("\"")-1);
            SendSmsResponse sendSmsResponse = gson.fromJson(substring, SendSmsResponse.class);
            logger.debug("sendSmsResponse is : {}",sendSmsResponse);
            return sendSmsResponse;
        }catch (ClientException ex){
            logger.error("" + ex);
        }
        return null;
    }

    public static boolean sendSmsBatch(String phoneNumberJson,Integer size,String content) throws ClientException {
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", SMS_ACCESSKEY_ID,
            SMS_SECRET);
//        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AppSettingsHelper.getSmsAccesskeyId(),
//                AppSettingsHelper.getSmsSecret());
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        SendBatchSmsRequest request = new SendBatchSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持JSON格式的批量调用，批量上限为100个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        request.setPhoneNumberJson(phoneNumberJson);
        //必填:短信签名-支持不同的号码发送不同的短信签名
        request.setSignNameJson(buildSignNameJson(size));
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(SMS_TEMPLATE_CODE);
        //必填:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        request.setTemplateParamJson(buildParam(size,content));
        //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCodeJson("[\"90997\",\"90998\"]");
        //请求失败这里会抛ClientException异常
        SendBatchSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        logger.debug("SendBatchSmsResponse : {}",sendSmsResponse.getCode());
        logger.debug("SendBatchSmsResponse : {}",sendSmsResponse.getMessage());
        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            //请求成功
            return true ;
        }
        return false;
    }

    private static String buildSignNameJson(int size){
        return convertListJson(SMS_SIGN_NAME,size);
    }

    private static String buildParam(int size,String content){
        String templateParam = SMS_TEMPLATE_PARAM.replaceAll("123456",content);
        return convertListJson(templateParam,size);
    }

    private static String convertListJson(String content, int size){
        Gson gson = new GsonBuilder().create();
        List<String> list = new ArrayList<>();
        for(int i=0; i<size; i++){
            list.add(content);
        }
        return gson.toJson(list);
    }


    public static void main(String args[]) throws ClientException {

        String data = "{}{\"Message\":\"OK\",\"RequestId\":\"0FFB21E3-3F3D-4F7C-8422-1192B26C9DCA\",\"BizId\":\"280811497632396513^0\",\"Code\":\"OK\"}";
        String substring = data.substring(data.indexOf("\"")-1);
        System.out.println(substring);

        SendSmsResponse sendSmsResponse = gson.fromJson(substring, SendSmsResponse.class);
        System.out.println(sendSmsResponse);

//        sendWithDrawSms("13413308888","12345","123","网购省钱验证",SMS_WITH_TEMPLATE_CODE);
//        doSendSms("18819258225","{\"code\":\"236578\",\"product\":\"网购省钱\"}",SMS_SIGN_NAME,SMS_TEMPLATE_CODE);
//        sendSms("18819258225","123654");
    }
}
